#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <semaphore.h>
#include <string>
#include <fstream>
#include <sys/time.h>

#define millitime(x) (x.tv_sec * 1000 + x.tv_usec / 1000.0)
#define abs(x) ((x < 0) ? -(x) : (x))
#define MaxN 1000

using namespace std;
void init() {
    A = new float*[n];
    mother = new float*[n];
    for (int i = 0; i < n; i++) {
        A[i] = new float[n];
        mother[i] = new float[n];
        for (int j = 0; j < n; j++) {
            A[i][j] = 0;
            mother[i][j] = (j == i) ? 1 : i + j;
        }
    }
    for (int i = 1; i < n; i++)
        for (int j = 0; j < i; j++)
            for (int k = 0; k < n; k++)
                A[i][k] += mother[j][k];
}

// 重置矩阵 A 为初始状态
void arr_reset() {
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            A[i][j] = mother[i][j];
}

// 释放矩阵内存
void release_matrix() {
    for (int i = 0; i < n; i++) {
        delete[] A[i];
        delete[] mother[i];
    }
    delete[] A;
    delete[] mother;
}

// 验证高斯消去法的结果
void testResult() {
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            if (abs(A[i][j] - mother[i][j]) >= 1e-6) {
                cout << "结果错误！" << endl;
                cout << i << ' ' << j << ' ' << A[i][j] << ' ' << mother[i][j] << endl;
                exit(-1);
            }
}

// 测试并测量高斯消去法函数的性能
void test(void (*f)(), const string &path) {
    int counter = 0;
    timeval begin, start, finish, now;
    float milliseconds = 0, single_time;
    gettimeofday(&begin, NULL);
    gettimeofday(&now, NULL);
    while (millitime(now) - millitime(begin) < 20) {
        counter++;
        arr_reset();
        gettimeofday(&start, NULL);
        f();
        gettimeofday(&finish, NULL);
        milliseconds += (millitime(finish) - millitime(start));
        gettimeofday(&now, NULL);
    }
    testResult();
    single_time = milliseconds / counter;
    cout << counter << " " << single_time << endl;
    ofstream out_file(path, ios::app);
    out_file << single_time << ' ';
    out_file.close();
}

// 线程参数结构体
struct threadParam_td {
    int k;
    int t_id;
};

int n, thread_count;
float **A = NULL, **mother = NULL;
sem_t *sem_Division, *sem_Elimination, sem_leader;
pthread_barrier_t barrier;

int main(int argc, char *argv[]) {
    if (argc < 2) {
        cerr << "Usage: " << argv[0] << " <thread_count>" << endl;
        return -1;
    }

    thread_count = atoi(argv[1]);
    string paths[] = {"平凡算法", "动态线程优化", "静态线程信号量优化", "静态线程 barrier 优化"};
    void (*functions[])() = {common_gauss, dynamic_gauss, static_gauss_sem, static_gauss_barrier};

    n = 10;
    while (n <= MaxN) {
        init();
        cout << "n: " << n << endl;
        for (int i = 0; i < 4; i++) {
            string path = paths[i] + ".txt";
            cout << path << ": ";
            test(functions[i], path);
        }
        release_matrix();
        if (n < 100) n += 10;
        else n += 100;
    }
    return 0;
}
